<?php
/**
 * 权限管理控制器
 * PHP version 5
 * @package   Antonia
 * @author    Antonia <471699715@qq.com>
 * @copyright 2016 Antonia.
 */
namespace Admin\Controller;
use Think;
class RegionController extends AdmincommonController {
    /**
     * 显示列表
     * @param HttpRequest $request
     * @return void
     * @author Antonia
     */
    public function index() {
        $region = D("Regions");
        $list  = $region->where('parent_id=0')
                        ->select();
        if($list) {
            $newlist = array();
            $parent_ids = array();
            foreach ($list as $l) {
                $parent_ids[] = $l["region_id"];
            }
            //2级
            if(!empty($parent_ids)) {
                $chirdMap = array();
                $chirdMap["parent_id"] = array("in", $parent_ids);
                $chirdren = $region->order('region_id desc')
                                    ->where($chirdMap)
                                    ->select();
                //3级
                $parent_ids = array();
                foreach ($chirdren as $c) {
                    $parent_ids[] = $c["region_id"];
                }
                if(!empty($parent_ids)) {
                    $chirdMap = array();
                    $chirdMap["parent_id"] = array("in", $parent_ids);
                    $chirdrenren = $region->order('region_id desc')
                                        ->where($chirdMap)
                                        ->select();
                    $twoArr = array();
                    foreach ($chirdrenren as $cc) {
                        $parent_id = $cc["parent_id"];
                        $twoArr[$parent_id][] = $cc;
                    }
                }
                $oneArr = array();
                foreach($chirdren as $c) {
                    $rid = $c["region_id"];
                    $parent_id = $c["parent_id"];
                    $c["chirdren"] = $twoArr[$rid];
                    $oneArr[$parent_id][] = $c;
                }
            }
            foreach($list as $l) {
                $rid = $l["region_id"];
                $l["chirdren"] = $oneArr[$rid];
                $newlist[] = $l;
            }
        }
        $this->assign('list',$newlist);
        $this->display();
    }

    /**
     * 显示新增页面
     * @param HttpRequest $request
     * @return void
     * @regionor Antonia
    */
    public function add() {
        $list = D("Regions")->where("parent_id=0")
                                ->field("region_id,region_name")
                                ->select();
        $this->assign("clist", $list);
        $this->display('info');
    }

    /**
     * 处理新增
     * @param HttpRequest $request
     * @return void
     * @author Antonia
    */
    public function insert() {
        $region = D("Regions");
        if ($vo = $region->create()) {
            unset($vo["region_id"]);

            if(!empty($vo["parent_id"])) {
                $parent_info = $region->field("lv")->find($vo["parent_id"]);
                $vo["lv"] = $parent_info["lv"] * 1 + 1;
            } else {
                $vo["parent_id"] = 0;
                $vo["lv"] = 1;
            }

            $rs = $region->add($vo);

            if ($rs !== false) {
                $re['statusCode'] = "200";
                $re['message'] = "新增成功!";
                $re['navTabId'] = "Regionindex";
                $re['callbackType'] = "closeCurrent";
            } else {
                $re['statusCode'] = "300";
                $re['message'] = "新增错误，请重试!";
            }
        } else {
                $re['statusCode'] = "300";
                $re['message'] = $region->getError();
        }
		
        echo json_encode($re);
    }

    /**
     * 显示编辑页面
     *
     * @param HttpRequest $request
     *
     * @return void
     * @author Antonia
    */
    public function edit() {
        $region_id = remove_xss($_GET['id']);
        if (!empty($region_id)) {
            $Regions     = D("Regions");
            $regionInfo  = $Regions->find($region_id);
            if ($regionInfo) {
                if(!empty($regionInfo['parent_id'])) {
                    if($regionInfo['lv'] == 1) {
                        $regionInfo["country_id"] = 0;
                    } else if($regionInfo['lv'] == 2) {
                        $regionInfo["country_id"] = $regionInfo['parent_id'];
                        $regionInfo["city_id"] = 0;
                        $city_list = $Regions->field("region_id,region_name")
                                                ->where("parent_id=".$regionInfo['parent_id'])
                                                ->select();
                        $this->assign('city_list', $city_list);
                    } else {
                        $regionInfo["city_id"] = $regionInfo['parent_id'];
                        $cityinfo = $Regions->field("parent_id")->find($regionInfo['parent_id']);
                        if(!empty($cityinfo)) {
                            $regionInfo["country_id"] = $cityinfo['parent_id'];
                            $city_list = $Regions->field("region_id,region_name")
                                                    ->where("parent_id=".$cityinfo['parent_id'])
                                                    ->select();
                            $this->assign('city_list', $city_list);
                        }
                    }
                }
                $parent_map = array();
                $parent_map["parent_id"] = 0;
                $parent_map["region_id"] = array("neq", $region_id);
                $list = $Regions->where($parent_map)
                        ->field("region_id,region_name")
                        ->select();
                $this->assign("clist", $list);

                $this->assign('regioninfo', $regionInfo);
                $this->display('info');
            } else {
                $re['statusCode'] = "300";
                $re['navTabId'] = "regionindex";
                $re['callbackType'] = "closeCurrent";
                $re['message'] = "该记录不存在！";
                echo json_encode($re);
            }
        } else {
            $re['statusCode'] = "300";
            $re['navTabId'] = "Regionindex";
            $re['callbackType'] = "closeCurrent";
            $re['message'] = "该记录不存在！";
            echo json_encode($re);
        }
    }

    /**
     * 处理更新数据
     * @param HttpRequest $request
     * @return void
     * @author Antonia
    */
    public function update() {
        $region = D("Regions");
        if ($vo = $region->create()) {
            $info = $region->field("lv")->find($vo["region_id"]);
            if(!$info) {
                $re['statusCode'] = "300";
                $re['message'] = "该记录不存在";
                echo json_encode($re);
                exit;
            }
            if(!empty($vo["parent_id"])) {
                $parent_info = $region->field("lv")->find($vo["parent_id"]);
                $vo["lv"] = $parent_info["lv"] * 1 + 1;
            } else {
                $vo["parent_id"] = 0;
                $vo["lv"] = 1;
            }
            $list = $region->save($vo);
            if ($list !== false) {
                if($info["lv"] == 1) {
                    $list = $region->where("parent_id=".$vo["region_id"])
                                    ->field("region_id")
                                    ->select();
                    $parent_ids = array();
                    foreach ($list as $l) {
                        $parent_ids[] = $l["region_id"];
                    }
                    if(!empty($parent_ids)) {
                        $chirdMap = array();
                        $chirdMap["parent_id"] = array("in", $parent_ids);
                        $lv = $vo["lv"] + 1;
                        $region->where($chirdMap)->setField("lv", $lv+1);
                        $chirdMap = array();
                        $chirdMap["region_id"] = array("in", $parent_ids);
                        $region->where($chirdMap)->setField("lv", $lv);
                    }
                } elseif($info["lv"] == 2) {
                    $list = $region->where("parent_id=".$vo["region_id"])
                                    ->field("region_id")
                                    ->select();
                    $parent_ids = array();
                    foreach ($list as $l) {
                        $parent_ids[] = $l["region_id"];
                    }
                    if(!empty($parent_ids)) {
                        $chirdMap = array();
                        $chirdMap["region_id"] = array("in", $parent_ids);
                        $lv = $vo["lv"] + 1;
                        $region->where($chirdMap)->setField("lv", $lv);
                    }
                }
                $re['statusCode'] = "200";
                $re['message'] = "修改成功!";
                $re['navTabId'] = "Regionindex";
                $re['callbackType'] = "closeCurrent";
            } else {
                $re['statusCode'] = "300";
                $re['message'] = "没有更新任何数据!";
            }
        } else {
                $re['statusCode'] = "300";
                $re['message'] = $region->getError();
        }

        echo json_encode($re);
    }


    /**
     * 获取子级地区
     * @param HttpRequest $request
     * @return void
     * @author Antonia
     */
    public function getRegions() {
        if(!empty($_POST["parent_id"])) {
            $parent_id = intval($_POST["parent_id"]);
            $list = D("Regions")->where("parent_id=".$parent_id)
                                ->field("region_id,region_name")
                                ->select();
            
            $str = "<select class='regioncitys'>";
            $str .= "<option value='0'>全部地区</option>";
            foreach($list as $l) {
                $str .= "<option value='".$l["region_id"]."'>".$l["region_name"]."</option>";
            }
            $str .= "</select>";
            
            $this->ajaxReturn($str,'success',1);
        } else {
            $this->ajaxReturn(array(),'error',0);
        }
    }

    /**
     * 删除
     * @param HttpRequest $request
     * @return void
     * @author Antonia
    */
    public function delete() {
        if (!empty($_GET['id'])) {
            $region = D("Regions");
            $id = intval($_GET['id']);
            $info = $region->field("lv")->find($id);
            if($info["lv"] == 1) {
                $list = $region->where("parent_id=".$id)
                                ->field("region_id")
                                ->select();
                $parent_ids = array();
                foreach ($list as $l) {
                    $parent_ids[] = $l["region_id"];
                }
                if(!empty($parent_ids)) {
                    $chirdMap = array();
                    $chirdMap["parent_id"] = array("in", $parent_ids);
                    $region->where($chirdMap)->delete();
                    $chirdMap = array();
                    $chirdMap["region_id"] = array("in", $parent_ids);
                    $region->where($chirdMap)->delete();
                }
            } elseif($info["lv"] == 2) {
                $list = $region->where("parent_id=".$id)->delete();
            }
            $result = $region->delete($id);
            if (false !== $result) {
                $re['statusCode'] = "200";
                $re['message'] = "删除成功!";
            } else {
                $re['statusCode'] = "300";
                $re['message'] = "删除失败，请重试!";
            }
        } else {
                $re['statusCode'] = "300";
                $re['message'] = "该记录不存在！";;
        }
        echo json_encode($re);
    }
}
?>